//
//  RotatorView.m
//  PictureRotator
//
//  Created by ZJ on 2018/7/30.
//  Copyright © 2018年 iCatch Technology Inc. All rights reserved.
//

#import "RotatorView.h"

static const NSTimeInterval RotatorViewPictureRotatorInterval = 1.5;

@interface RotatorView () <UIScrollViewDelegate>

@property (nonatomic, weak) UIScrollView *scrollView;
@property (nonatomic, weak) UIPageControl *pageControl;
@property (nonatomic, strong) NSArray<UIImage *> *images;
@property (nonatomic, strong) NSTimer *rotatorTimer;

@end

@implementation RotatorView

#pragma mark - Init
- (instancetype)initWithimages:(NSArray<UIImage *> *)images offsetY:(CGFloat)offsetY height:(CGFloat)height
{
    self = [super initWithFrame:CGRectMake(0, offsetY, CGRectGetWidth(UIScreen.mainScreen.bounds), height)];
    if (self) {
        self.images = images;
        [self setupGUI];
    }
    return self;
}

- (void)dealloc {
    [self releaseTimer];
}

#pragma mark - Setup Properties
- (void)setPageIndicatorTintColor:(UIColor *)pageIndicatorTintColor {
    _pageIndicatorTintColor = pageIndicatorTintColor ? pageIndicatorTintColor : [UIColor blueColor];
    
    _pageControl.pageIndicatorTintColor = _pageIndicatorTintColor;
}

- (void)setCurrentPageIndicatorTintColor:(UIColor *)currentPageIndicatorTintColor {
    _currentPageIndicatorTintColor = currentPageIndicatorTintColor ? currentPageIndicatorTintColor : [UIColor redColor];
    
    _pageControl.currentPageIndicatorTintColor = _currentPageIndicatorTintColor;
}

- (void)setRotatorInterval:(NSTimeInterval)rotatorInterval {
    BOOL isEqualDefaultInterval = rotatorInterval == RotatorViewPictureRotatorInterval;
    BOOL isEqualZero = rotatorInterval == 0;
    BOOL isInValid =  isEqualZero || isEqualDefaultInterval;
    
    if (isInValid) {
        return;
    }
    
    _rotatorInterval = rotatorInterval;
    [self releaseTimer];
    [self rotatorTimer];
}

#pragma mark - setup GUI
- (void)setupGUI {
    [self setupScrollView];
    [self setupPageControl];
    [self setupImageViews];
    [self rotatorTimer];
}

- (void)setupScrollView {
    CGRect bounds = self.bounds;
    CGFloat margin = 10.0;
    CGFloat x = margin;
    CGFloat width = CGRectGetWidth(bounds) - margin * 2;
    CGFloat height = CGRectGetHeight(bounds);
    
    UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(x, 0.0, width, height)];
    
    scrollView.pagingEnabled = YES;
    scrollView.showsHorizontalScrollIndicator = NO;
    
    CGFloat maxW = width * _images.count;
    scrollView.contentSize = CGSizeMake(maxW, 0.0);
    
    scrollView.delegate = self;
//    scrollView.userInteractionEnabled = YES;
    
    _scrollView = scrollView;
    
    [self addSubview:scrollView];
}

- (void)setupPageControl {
    CGRect bounds = self.bounds;
    CGFloat width = 120;
    CGFloat height = 37;
    CGFloat x = (CGRectGetWidth(bounds) - width) * 0.5;
    CGFloat y = CGRectGetHeight(bounds) - height;
    
    UIPageControl *pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(x, y, width, height)];
    
    pageControl.numberOfPages = _images.count;
    pageControl.currentPage = 0;
    pageControl.pageIndicatorTintColor = [UIColor blueColor];
    pageControl.currentPageIndicatorTintColor = [UIColor redColor];
    
    _pageControl = pageControl;
    [self addSubview:pageControl];
}

- (void)setupImageViews {
    CGRect bounds = _scrollView.bounds;
    CGFloat imgW = CGRectGetWidth(bounds);
    CGFloat imgH = CGRectGetHeight(bounds);
    CGFloat imgY = 0;
    
    for (int i = 0; i < _images.count; i++) {
        UIImageView *imgView = [[UIImageView alloc] init];
        
        imgView.image = _images[i];
        
        CGFloat imgX = i * imgW;
        
        imgView.frame = CGRectMake(imgX, imgY, imgW, imgH);
        
        [_scrollView addSubview:imgView];
        
        imgView.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(imageViewClicked:)];
        [imgView addGestureRecognizer:tap];
    }
}

#pragma mark - Rotator Timer
- (NSTimer *)rotatorTimer {
    if (_rotatorTimer == nil) {
        NSTimeInterval interval = _rotatorInterval ? _rotatorInterval : RotatorViewPictureRotatorInterval;
        _rotatorTimer = [NSTimer scheduledTimerWithTimeInterval:interval target:self selector:@selector(scrollImage) userInfo:nil repeats:YES];
        
        // 修改定时器的优先级与控件一样
        // 默认情况下定时器的优先级要比控件的优先级低，如果用户一直操作UI，CPU将没有时间处理定时器的操作（定时器的操作线程将被阻塞）
        // NSRunLoopCommonModes 与UI的优先级一致
        // NSDefaultRunLoopMode 默认优先级
        NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
        // 改变定时器的优先级
        [runLoop addTimer:_rotatorTimer forMode:NSRunLoopCommonModes];
    }
    
    return _rotatorTimer;
}

- (void)releaseTimer {
    if (_rotatorTimer.valid) {
        [_rotatorTimer invalidate];
        _rotatorTimer = nil;
    }
}

- (void)scrollImage {
    NSInteger page = self.pageControl.currentPage;
    
    if (page == self.pageControl.numberOfPages - 1) {
        page = 0;
    } else {
        page++;
    }
    
    CGFloat offsetX = page * CGRectGetWidth(self.scrollView.frame);
    [self.scrollView setContentOffset:CGPointMake(offsetX, 0) animated:YES];
}

#pragma mark - UIScrollViewDelege
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    [self releaseTimer];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    CGFloat offsetX = scrollView.contentOffset.x;
    CGFloat scrollViewW = CGRectGetWidth(scrollView.frame);
    
    offsetX += scrollViewW * 0.5;
    
    int page = offsetX / scrollViewW;
    
    self.pageControl.currentPage = page;
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    [self rotatorTimer];
}

#pragma mark - RotatorViewDelegate
- (void)imageViewClicked:(UITapGestureRecognizer *)tap {
    if ([self.delegate respondsToSelector:@selector(rotatorViewDidSelected:pictureIndex:)]) {
        NSInteger page = self.pageControl.currentPage;
        NSLog(@"Selected index: %ld", (long)page);
        
        [self.delegate rotatorViewDidSelected:self pictureIndex:page];
    }
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
